package dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import models.Group;

import org.bson.types.ObjectId;
import org.jongo.MongoCollection;

import uk.co.panaxiom.playjongo.PlayJongo;
import dao.GroupDao;

public class GroupDaoImpl implements GroupDao {

	private static final MongoCollection groups;
	static {
		groups = PlayJongo.getCollection("groups");
	}

	@Override
	public long count(Group group) {
		return groups.count();
	}

	@Override
	public void insert(Group group) {
		groups.save(group);
	}

	@Override
	public Group select(Group group) {
		return null;
	}

	@Override
	public List<Group> selectList(Group group) {
		List<Group> result = new ArrayList<Group>();
		if (group != null) {
			return new ArrayList<Group>();
		} else {
			Iterator<Group> iter = groups.find().as(Group.class).iterator();
			while (iter.hasNext()) {
				result.add(iter.next());
			}
		}
		return result;
	}

	@Override
	public List<Group> selectByUserId(String userId) {
		List<Group> result = new ArrayList<Group>();
		System.out.println("userId = "+userId);
		Iterator<Group> iter = groups.find("{users:#}}",new ObjectId(userId)).as(Group.class).iterator();
		while (iter.hasNext()) {
			result.add(iter.next());
		}
		return result;
	}
	
	@Override
	public List<Group> selectAll(){
		List<Group> result = new ArrayList<Group>();
		Iterator<Group> iter = groups.find().as(Group.class).iterator();
		while (iter.hasNext()) {
			result.add(iter.next());
		}
		return result;
	}
	
	@Override
	public Group selectById(String groupId){
		return groups.findOne(new ObjectId(groupId)).as(Group.class);
	}

}
